<template>
  <a-card>
    <!-- 查询   -->
    <a-form
        ref="searchFormRef"
        :model="search_form"
        @submit="handleSearchSubmit"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left">
      <a-row>
        <a-col :flex="1">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="用户名" field="username">
                <a-input placeholder="请输入用户名" v-model="search_form.username"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="电话号码" field="phoneNumber">
                <a-input placeholder="请输入电话号码" v-model="search_form.phoneNumber"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="邮箱" field="email">
                <a-input placeholder="请输入邮箱" v-model="search_form.email"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="角色" field="role">
                <a-select :style="{width:'320px'}" placeholder="请输入购买渠道" allow-create allow-clear
                          v-model="search_form.role">
                  <a-option value="M">管理员</a-option>
                  <a-option value="U">用户</a-option>
                  <a-option value="S">司机</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
            </a-col>
            <a-col :span="8">
            </a-col>
          </a-row>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search/>
              </template>
              查询
            </a-button>
            <a-button @click="$refs.searchFormRef.resetFields()">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider/>
      <!-- 添加操作   -->
      <a-row>
        <a-col :span="6" style="padding-bottom: 10px">
          <a-space>
            <a-button
                type="primary" shape="round" @click="addUserOpen">
              <template #icon>
                <icon-plus/>
              </template>
              <template #default>新增用户</template>
            </a-button>
            <a-button shape="round">
              导出表格
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" class="mb-1"></a-col>
      </a-row>
    </a-form>
    <!-- 信息展示   -->
    <a-table :columns="columns" :data="users"
             :pagination="pagination"
             @page-change="handlePaginationChange" style="height: 70vh">
      <template #username="{record,rowIndex}">
        <a-descriptions :column="1">
          <a-descriptions-item>
            {{ record.usernameWbxqy }}
          </a-descriptions-item>
          <a-descriptions-item>
            <a-avatar
                shape="square"
                :size="32">
              <img
                  alt="avatar"
                  :src="record.avatarUrlWbxqy"
              />
            </a-avatar>
          </a-descriptions-item>
        </a-descriptions>
      </template>
      <template #role="{record,rowIndex}">
        <a-tag v-if="record.roleWbxqy==='M'" style="border-radius: 20px; background-color: #8150A2;color:white">
          管理员
        </a-tag>
        <a-tag v-else-if="record.roleWbxqy==='U'" style="border-radius: 20px; background-color: #FF6A88;color:white">
          普通用户
        </a-tag>
        <a-tag v-else-if="record.roleWbxqy==='S'" style="border-radius: 20px; background-color: #6acbff;color:white">
          司机
        </a-tag>
      </template>
      <template #department="{record,rowIndex}">
        {{record.department.departmentNameWbxqy}}
      </template>
      <template #operations="{record,rowIndex}">
        <a-space>
          <a-button
              type="outline" @click="editUserOpen(record)">
            <template #icon>
              <icon-edit/>
            </template>
            编辑
          </a-button>
          <a-button
              type="outline" status="danger" @click="deleteUserFun(record.userIdWbxqy)">
            <template #icon>
              <icon-delete/>
            </template>
            删除
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 添加用户对话框   -->
    <a-modal v-model:visible="showAddUserModal" title="添加用户" @before-ok="addUserOk"
             @cancel="addUserCancel">
      <a-form ref="addUserFormRef" :model="addUserForm" :rules="rules">
        <a-form-item label="用户名" field="usernameWbxqy">
          <a-input v-model="addUserForm.usernameWbxqy"/>
        </a-form-item>
        <a-form-item label="密码" field="passwordWbxqy">
          <a-input type="password" v-model="addUserForm.passwordWbxqy"/>
        </a-form-item>
        <a-form-item label="头像" field="avatarUrlWbxqy">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-upload
                :action="uploadUrl"
                :fileList="avatar ? [avatar] : []"
                :show-file-list="false"
                @change="onChange"
                @success="onSuccess"
                @progress="onProgress"
            >
              <template #upload-button>
                <div
                    :class="`arco-upload-list-item${
            avatar && avatar.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
                >
                  <div
                      class="arco-upload-list-picture custom-upload-avatar"
                      v-if="avatar && avatar.url"
                  >
                    <img :src="avatar.url"/>
                    <div class="arco-upload-list-picture-mask">
                      <IconEdit/>
                    </div>
                    <a-progress
                        v-if="avatar.status === 'uploading' && avatar.percent < 100"
                        :percent="avatar.percent"
                        type="circle"
                        size="mini"
                        :style="{
                position: 'absolute',
                left: '50%',
                top: '50%',
                transform: 'translateX(-50%) translateY(-50%)',
              }"
                    />
                  </div>
                  <div class="arco-upload-picture-card" v-else>
                    <div class="arco-upload-picture-card-text">
                      <IconPlus/>
                      <div style="margin-top: 10px; font-weight: 600">上传头像</div>
                    </div>
                  </div>
                </div>
              </template>
            </a-upload>
          </a-space>
        </a-form-item>
        <a-form-item label="角色" field="roleWbxqy">
          <a-select :style="{width:'320px'}" placeholder="请选择用户的角色" v-model="addUserForm.roleWbxqy"
                    allow-clear>
            <a-option value="M">管理员</a-option>
            <a-option value="U">普通用户</a-option>
            <a-option value="S">司机</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="部门" field="departmentIdWbxqy">
          <a-select :style="{width:'320px'}" placeholder="请选择用户的角色" v-model="addUserForm.departmentIdWbxqy"
                    allow-clear>
            <a-option
                v-for="item in departments"
                :key="item.departmentIdWbxqy"
                :value="item.departmentIdWbxqy"
            >
              {{ item.departmentNameWbxqy }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="邮箱" field="emailWbxqy">
          <a-input v-model="addUserForm.emailWbxqy"/>
        </a-form-item>
        <a-form-item label="电话号码" field="phoneNumberWbxqy">
          <a-input v-model="addUserForm.phoneNumberWbxqy"/>
        </a-form-item>

      </a-form>
    </a-modal>
    <!-- 编辑用户对话框   -->
    <a-modal v-model:visible="showEditUserModal" title="编辑用户" @before-ok="editUserOk"
             @cancel="editUserCancel">
      <a-form ref="editUserFormRef" :model="editUserForm" :rules="rules">
        <a-form-item label="用户名" field="usernameWbxqy">
          <a-input v-model="editUserForm.usernameWbxqy"/>
        </a-form-item>
        <a-form-item label="密码" field="passwordWbxqy">
          <a-input type="password" v-model="editUserForm.passwordWbxqy"/>
        </a-form-item>
        <a-form-item label="头像" field="avatarUrlWbxqy">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-upload
                :action="uploadUrl"
                :fileList="editAvatar ? [editAvatar] : []"
                :show-file-list="false"
                @change="onEditChange"
                @success="onEditSuccess"
            >
              <template #upload-button>
                <div
                    :class="`arco-upload-list-item${
            editAvatar && editAvatar.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
                >
                  <div
                      class="arco-upload-list-picture custom-upload-avatar"
                      v-if="editAvatar && editAvatar.url"
                  >
                    <img :src="editAvatar.url"/>
                    <div class="arco-upload-list-picture-mask">
                      <IconEdit/>
                    </div>
                    <a-progress
                        v-if="editAvatar.status === 'uploading' && editAvatar.percent < 100"
                        :percent="editAvatar.percent"
                        type="circle"
                        size="mini"
                        :style="{
                position: 'absolute',
                left: '50%',
                top: '50%',
                transform: 'translateX(-50%) translateY(-50%)',
              }"
                    />
                  </div>
                  <div class="arco-upload-picture-card" v-else>
                    <div class="arco-upload-picture-card-text">
                      <IconPlus/>
                      <div style="margin-top: 10px; font-weight: 600">上传头像</div>
                    </div>
                  </div>
                </div>
              </template>
            </a-upload>
          </a-space>
        </a-form-item>
        <a-form-item label="角色" field="roleWbxqy">
          <a-select :style="{width:'320px'}" placeholder="请选择用户的角色" v-model="editUserForm.roleWbxqy"
                    allow-clear>
            <a-option value="M">管理员</a-option>
            <a-option value="U">普通用户</a-option>
            <a-option value="S">司机</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="部门" field="departmentIdWbxqy">
          <a-select :style="{width:'320px'}" placeholder="请选择用户的角色" v-model="editUserForm.departmentIdWbxqy"
                    allow-clear>
            <a-option
                v-for="item in departments"
                :key="item.departmentIdWbxqy"
                :value="item.departmentIdWbxqy"
            >
              {{ item.departmentNameWbxqy }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="邮箱" field="emailWbxqy">
          <a-input v-model="editUserForm.emailWbxqy"/>
        </a-form-item>
        <a-form-item label="电话号码" field="phoneNumberWbxqy">
          <a-input v-model="editUserForm.phoneNumberWbxqy"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {addUser, getAllUsers, deleteUser, updateUser} from '@/api/userMG';
import {listDepartments} from '@/api/departmentMG.js';
import {Message} from "@arco-design/web-vue";
import {IconEdit, IconPlus,IconSearch,IconRefresh,IconDelete} from '@arco-design/web-vue/es/icon';

const users = ref([]);
const departments = ref([])
const pagination = ref({
  current: 1,   // 当前页数
  pageSize: 10, // 每页条数
  total: 0      // 数据总数
});
const columns = [
  {title: 'ID', dataIndex: 'userIdWbxqy'},
  {title: '用户名', dataIndex: 'usernameWbxqy', slotName: 'username'},
  {title: '角色', dataIndex: 'roleWbxqy', slotName: 'role'},
  {title: '部门', dataIndex: 'departmentIdWbxqy', slotName: 'department'},
  {title: '邮箱', dataIndex: 'emailWbxqy'},
  {title: '电话号码', dataIndex: 'phoneNumberWbxqy'},
  {
    title: '操作',
    dataIndex: 'operation',
    width: '150',
    align: 'center',
    slotName: 'operations',
    fixed: 'right'
  }
];
// 添加用户
const addUserFormRef = ref(null)
const showAddUserModal = ref(false);
const addUserForm = reactive({
  usernameWbxqy: '',
  passwordWbxqy: '',
  roleWbxqy: '',
  departmentIdWbxqy: '',
  emailWbxqy: '',
  phoneNumberWbxqy: '',
  avatarUrlWbxqy: ''
});
const rules = {
  usernameWbxqy: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
  ],
  passwordWbxqy: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
  ],
  roleWbxqy: [
    {required: true, message: '角色不能为空', trigger: 'change'}
  ],
  emailWbxqy: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
  ],
  phoneNumberWbxqy: [
    {required: true, message: '电话号码不能为空', trigger: 'blur'},
  ],
  avatarUrlWbxqy: [
    {required: false, message: '头像地址为选填项', trigger: 'blur'}
  ]
};
const addUserOpen = async () => {
  showAddUserModal.value = true
  departments.value = await listDepartments()
}
const addUserOk = async (done) => {
  //进行表单校验
  const res = await addUserFormRef.value.validate();
  if (res) {
    done(false);
    return;
  }
  // 清除值为空的属性
  for (const key in addUserForm) {
    if (addUserForm[key] === '') {
      delete addUserForm[key];
    }
  }
  await addUser(addUserForm).then(res => {
    done()
    Message.success({
      content: "添加用户成功",
      duration: "3000"
    })
    // 清空数据
    addUserFormRef.value.resetFields()
    // 初始加载数据
    fetchUsers()
  }).catch(error => {
    done(false)
    this.$message.error(error)
  })
}
const addUserCancel = async () => {
  showAddUserModal.value = false
}
// 上传头像
const avatar = ref();
const uploadUrl = 'http://localhost:9999/upload'; // 替换为你的上传URL
const onChange = (_, currentFile) => {
  avatar.value = {
    ...currentFile,
  };
};

const onSuccess = (value) => {
  addUserForm.avatarUrlWbxqy = value.response.url
}

// 编辑用户
const showEditUserModal = ref(false);
const editUserFormRef = ref(null);
const editUserForm = reactive({
  userIdWbxqy: '',
  usernameWbxqy: '',
  passwordWbxqy: '',
  roleWbxqy: '',
  departmentIdWbxqy: '',
  emailWbxqy: '',
  phoneNumberWbxqy: '',
  avatarUrlWbxqy: ''
});

const editUserOpen = async (record) => {
  Object.assign(editUserForm, record);
  departments.value = await listDepartments()
  showEditUserModal.value = true;
};

const editUserOk = async (done) => {
  //进行表单校验
  const res = await editUserFormRef.value.validate();
  if (res) {
    done(false);
    return;
  }
  // 清除值为空的属性
  for (const key in editUserForm) {
    if (editUserForm[key] === '') {
      delete editUserForm[key];
    }
  }
  await updateUser(editUserForm).then(res => {
    done()
    Message.success({
      content: "数据更新成功",
      duration: "3000"
    })
    // 清空数据
    editUserFormRef.value.resetFields()
    // 初始加载数据
    fetchUsers()
  }).catch(error => {
    done(false)
    this.$message.error(error)
  })
}

const editUserCancel = async () => {
  showEditUserModal.value = false
}

// 上传头像（编辑）
const editAvatar = ref();
const onEditChange = (_, currentFile) => {
  editAvatar.value = {
    ...currentFile,
  };
};

const onEditSuccess = (value) => {
  editUserForm.avatarUrlWbxqy = value.response.url
}

// 删除用户
const deleteUserFun = async (id) => {
  await deleteUser(id).then(res => {
    Message.success({
      content: "用户删除成功",
      duration: "3000"
    })
    fetchUsers()
  }).catch(error => {
    this.$message.error(error)
  })
}
//---------------------------搜索框相关-----------------------------------
const searchFormRef = ref(null);
const search_form = ref({
  username: '',
  phoneNumber: '',
  email: '',
  role: '',
})
const handleSearchSubmit = async ({values, errors}) => {
  await fetchUsers(values)
}
const fetchUsers = async (params) => {
  let res = await getAllUsers(params)
  // 获取数据
  users.value = res.records
  // 获取分页
  pagination.value.total = res.total;
  pagination.value.current = res.current;
};

// 处理表格变化的事件
const handlePaginationChange = async (page, pageSize) => {
  await fetchUsers({page: page, ...search_form.value});
};


onMounted(async () => {
  await fetchUsers()
})

</script>
<style scoped>
</style>
